<template>
  <el-dialog width="65%" v-model="dialogVisible">
    <template #header>
      <p class="title">设备明细</p>
      <p class="title-s">共激活{{ state.count }}台设备，在线{{ state.online_count }}台，离线{{ state.offline_count }}台</p>
    </template>
    <el-form :model="state.form" :inline="true" class="my-form">
      <el-form-item label="设备">
        <el-input clearable v-model="state.form.device_search" style="width: 280px;" placeholder="输入编号，主板编号，SN，网卡编号搜索" />
      </el-form-item>
      <el-form-item label="运营状态">
        <el-select clearable v-model="state.form.device_status" style="width: 85px;">
          <el-option :label="item.val" :value="item.key" v-for="item in state.deviceStatusEnum" :key="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="在线状态">
        <el-select clearable v-model="state.form.is_online" style="width: 85px;">
          <el-option :label="item.val" :value="item.key" v-for="item in state.deviceOnlineEnum" :key="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="激活时间">
        <el-date-picker style="width: 240px;" v-model="state.selectData" :editable="false" start-placeholder="结束时间"
          end-placeholder="结束时间" type="daterange" range-separator="至" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" :loading="btnLoading" icon="Search">搜索</el-button>
        <el-button type="primary" @click="myExport" :loading="state.exportLoading" icon="Download">导出</el-button>
      </el-form-item>
    </el-form>
    <!-- table -->
    <el-table border :data="deviceDataList" v-loading="loadingData" size="small">
      <el-table-column v-for="(item, index) in tableProps" align="center" :width="item.width || ''" :key="index"
        :label="item.label" :prop="item.prop"></el-table-column>
    </el-table>
    <div class="page flexCenter">
      <el-pagination background layout="prev, pager, next,jumper,total" @current-change="pageChange"
        @prev-click="pageChange" @next-click="pageChange" :total="state.count" :page-size="state.searchLimit.limit" />
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, watchEffect, onBeforeMount, watch } from 'vue';
import { getDeviceStatusEnum, deviceList } from '@/api/merchantManage/merchantManage';
import { isEmpty } from 'lodash-es';
import { useCommonStore } from '@/stores';
import { exportExcel } from '@/utils/exportExcel';
import { ElMessage } from 'element-plus';

const props = defineProps({
  isLoading: {
    type: Boolean,
    default: false
  }
})

const commonStore = useCommonStore();
const dialogVisible = ref(false)
const loadingData = ref(false);
const btnLoading = ref(false);
const state = reactive({
  form: {
    client_no: '',
    device_search: "",
    device_status: "",
    is_online: "",
    start_time: "",
    end_time: ""
  },
  searchLimit: {
    page: 1,
    limit: 8,
  },
  exportLoading: false,
  exportLimit: {
    page: 1,
    limit: 200,
    pageCount: 1
  },
  count: 0,
  offline_count: 0,
  online_count: 0,
  selectData: [],
  deviceStatusEnum: [],
  deviceOnlineEnum: []
})

const tableProps = ref([
  { label: '设备编号', prop: 'sticker_num', width: 80 },
  { label: '主板编号', prop: 'motherboard_num', width: 90 },
  { label: '网卡编号', prop: 'network_card', width: 90 },
  { label: 'POS机SN号', prop: 'pos_sn_no' },
  { label: '型号', prop: 'cabinet_model', width: 100 },
  { label: '运营状态', prop: 'device_status_label', width: 80 },
  { label: '在线状态', prop: 'online_status_label', width: 80 },
  { label: '离线时间', prop: 'offline_time', width: 140 },
  { label: '信号值', prop: 'network_strength', width: 70 },
  { label: '激活时间', prop: 'activation_time', width: 140 }
])

const deviceDataList = ref([])

// methods
const search = async () => {
  btnLoading.value = true;
  getList()
}

const getList = async () => {
  loadingData.value = true;
  const res = await deviceList({ ...state.searchLimit, ...state.form })
  if (res.code === 1000) {
    deviceDataList.value = res.data.listData.list
    state.count = res.data.listData.count
    state.offline_count = res.data.offline_count
    state.online_count = res.data.online_count
  }
  btnLoading.value = false;
  loadingData.value = false;
}

const pageChange = (page) => {
  state.searchLimit.page = page
  getList()
}


// 导出
let excelData = [];
const myExport = async () => {
  state.exportLoading = true;
  const res = await deviceList({ ...state.searchLimit, ...state.form, ...state.exportLimit });
  let exportData = [];
  let fileName = '设备列表';
  if (res.code === 1000) {
    // fileName += state.exportLimit.page;
    exportData = res.data.listData.list;
    state.exportLimit.pageCount = res.data.listData.pageCount;
  } else {
    ElMessage.error(res.message);
    state.exportLoading = false;
    return exportData = [];
  }
  
  const propList = [
    { label: '设备编号', prop: 'sticker_num' },
    { label: '主板编号', prop: 'motherboard_num' },
    { label: '网卡编号', prop: 'network_card' },
    { label: 'POS机SN号', prop: 'pos_sn_no' },
    { label: '所属商家编号', prop: 'client_no' },
    { label: '所属商家名称', prop: 'client_name' },
    { label: '型号', prop: 'cabinet_model' },
    { label: '运营状态', prop: 'device_status_label' },
    { label: '在线状态', prop: 'online_status_label' },
    { label: '离线时间', prop: 'offline_time' },
    { label: '信号值', prop: 'network_strength' },
    { label: '激活时间', prop: 'activation_time' }
  ]
  if(!excelData[0]){
    excelData[0] = propList.map(item => item.label);
  }
  for (let i = 0; i < exportData.length; i++) {
    excelData.push(propList.map(item => {
      if (item.prop.indexOf('.') > -1) {
        return exportData[i][item.prop.split('.')[0]]?.[item.prop.split('.')[1]] || '';
      }
      return exportData[i][item.prop] || ''
    }))
  }
  if (state.exportLimit.page < state.exportLimit.pageCount) {
    state.exportLimit.page++
    myExport();
  } else {
    // ElMessage.success('导出完成');
    state.exportLoading = false;
    state.exportLimit.page = 1;
    state.exportLimit.pageCount = 1;
    exportExcel(excelData, 'sheet1', `${fileName}.xlsx`);
    excelData = [];
  }
}


defineExpose({
  dialogVisible,
  state
})

watchEffect(() => {
  if (!isEmpty(state.selectData)) {
    state.form.start_time = state.selectData[0]
    state.form.end_time = state.selectData[1]
  } else {
    state.form.start_time = ''
    state.form.end_time = ''
  }


})

watch(dialogVisible, (dialogVisible) => {
  if (dialogVisible) {
    getList()
  }
})

// life
onBeforeMount(async () => {
  // 初始化数据
  if (!isEmpty(commonStore.deviceStatusEnum)) {
    state.deviceStatusEnum = commonStore.deviceStatusEnum.status;
    state.deviceOnlineEnum = commonStore.deviceStatusEnum.online;
  } else {
    const res = await getDeviceStatusEnum()
    if (res.code === 1000) {
      state.deviceStatusEnum = res.data.status;
      state.deviceOnlineEnum = res.data.online;
    }
    commonStore.deviceStatusEnum = res.data;
  }
})
</script>
<style lang="less" scoped>
.page {
  margin: 20px;
}

.title {
  line-height: var(--el-dialog-font-line-height);
  font-size: var(--el-dialog-title-font-size);
  color: var(--el-text-color-primary);
}

.title-s {
  margin-top: 5px;
  font-size: var(--el-form-label-font-size);
  color: var(--el-text-color-regular)
}
</style>